package com.share.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * mock一些临时数据
 */
public class IdCardUtil {
    private static final Map<String, Map<String, Object>> provinceMap = new HashMap();
    private static final String cityCode[][] = {
            //省份编号,省份名称,城市编号
            {"11", "北京市", "0100=市辖区&0101=东城区&0102=西城区&0105=朝阳区&0108=海淀区"}, {"12", "天津市", "0110=东丽区&0108=汉沽区&0104=南开区&0102=河东区&0114=武清区"}, {"42", "湖北省", "0100=武汉市&0200=黄石市&1100=黄冈市&0300=十堰市&9004=仙桃市"}, {"31", "上海市", "0114=宝山区&0116=浦东新&0106=静安区&0101=黄浦区&0113=闵行区"}, {"43", "湖南省", "0102=芙蓉区&0124=宁乡县&0181=浏阳市&0121=长沙县&0122=望城县"}, {"51", "四川省", "0100=成都市&0105=青羊区&0108=成华区&0104=锦江区&0107=武侯区"}, {"44", "广东省", "0106=天河区&5300=云浮市&5100=潮州市&1800=清远市&0112=黄埔区"}, {"14", "山西省", "2302=离石市&2322=文水县&2301=孝义市&2327=柳林县&2330=方山县"}};

    static {
        for (String[] arr : cityCode) {
            String province = arr[0];
            Map<String, Object> tmpMap = provinceMap.get(province);
            if (tmpMap == null) {
                tmpMap = new HashMap<>();
                provinceMap.put(province, tmpMap);
            }
            tmpMap.put("0", province);
            tmpMap.put("1", arr[1]);
            tmpMap.put("2", ParamUtil.kvToMap(arr[2]));
        }
    }

    //模板图片存储的位置
    private static final String BASE_URL = "http://share.snyq.ltd";

    //模板图片缓存map
    private static Map<String, byte[]> cacheMap = new HashMap<>();

    private static byte[] getImageByte(String url) throws Exception {
        byte[] bytes = cacheMap.get(url);
        if (bytes == null || bytes.length < 1) {
            synchronized (IdCardUtil.class) {
                byte[] tmpRes = HttpUtil.downFile(url, null);
                cacheMap.put(url, tmpRes);
            }
            return cacheMap.get(url);
        } else {
            return bytes;
        }
    }

    //通过身份证,返回一个便准地址
    public static String getAddress(String idCard) {
        String res = "";
        String privince = idCard.substring(0, 2);
        Map<String, Object> onePrivince = provinceMap.get(privince);
        if (!CollectionUtils.isEmpty(onePrivince)) {
            res += onePrivince.get("1");
            Map<String, String> cityMap = (Map<String, String>) onePrivince.get("2");
            if (!CollectionUtils.isEmpty(cityMap)) {
                String city = idCard.substring(2, 6);
                res += cityMap.get(city);
            }
        }
        return res + MockUtil.streetAddress();
    }

    //返回一个便准地址
    public static String getAddress() {
        String res = "";
        String privince = CollectionUtil.randomFromKey(provinceMap.keySet());
        Map<String, Object> onePrivince = provinceMap.get(privince);
        if (!CollectionUtils.isEmpty(onePrivince)) {
            res += onePrivince.get("1");
            Map<String, String> cityMap = (Map<String, String>) onePrivince.get("2");
            String city = CollectionUtil.randomFromKey(cityMap.keySet());
            res += cityMap.get(city);
        }
        return res + MockUtil.streetAddress();
    }

    public static String gen18() {
        String province = CollectionUtil.randomFromKey(provinceMap.keySet());

        Map<String, String> cityMap = (Map<String, String>) provinceMap.get(province).get("2");
        String city = CollectionUtil.randomFromKey(cityMap);

        Date date = DateExtUtil.addDay(new Date(), 0 - UUIDUtil.genRandomInt(60));
        String strDate = DateExtUtil.getDate(date);
        String id = province + city + strDate + UUIDUtil.genRandomNumber(4);
        return id;
    }

    //1男 0女
    public static String getSex(String idCard) {
        Character c = null;
        int len = 0;
        if (StringUtils.isNotBlank(idCard) && ((len = idCard.length()) > 16)) {
            if (len == 18) {
                c = idCard.charAt(len - 2);
            } else {
                c = idCard.charAt(len - 1);
            }
        }

        return c == null ? null : Integer.valueOf(c) % 2 + "";
    }

    public static String getBirthDay(String idCard) {
        String str = null;
        if (StringUtils.isNotBlank(idCard) && (idCard.length() > 16)) {
            str = idCard.substring(6, 14);
        }
        return str;
    }

    public static String getAge(String idCard) {
        String birthDay = getBirthDay(idCard);
        Date date2 = DateExtUtil.strD2Date(birthDay);
        Integer age = DateUtil.differYear(new Date(), date2);
        return age + "";
    }

    public static byte[] genFrontImage(String name, String idCard, String address) throws Exception {
        return genFrontImage(name, idCard, address, "汉");
    }

    //正面图片
    //key的格式： x_y_sognti_style_frontSize_R_G_B   value是写的字符串的值
    public static byte[] genFrontImage(String name, String idCard, String address, String nation) throws Exception {
        String url = BASE_URL + "/template/idCard_front.png";
        byte[] imageByte = getImageByte(url);
        if (imageByte == null || imageByte.length < 10) {
            return null;
        }

        //key的格式： x_y_sognti_style_frontSize_R_G_B   value是写的字符串的值
        Map<String, String> kv = new HashMap<>();
        String sex = "1".equals(getSex(idCard)) ? "男" : "女";
        String birthDay = new StringBuffer(getBirthDay(idCard)).insert(6, "        ").insert(4, "           ").toString();
        String address1 = null;
        String address2 = null;
        String address3 = null;
        if (address != null) {
            final int LINE_SIZE = 15;
            int c = address.length();
            if (c <= LINE_SIZE) {
                address1 = address;
            } else {
                if (c <= LINE_SIZE * 2) {
                    address1 = address.substring(0, LINE_SIZE);
                    address2 = address.substring(LINE_SIZE);
                } else {
                    address1 = address.substring(0, LINE_SIZE);
                    address2 = address.substring(LINE_SIZE, LINE_SIZE * 2);
                    address3 = address.substring(LINE_SIZE * 2);
                }
            }
        }

        kv.put(ImageUtil.getImageMapKey(100, 63, "songti", "bold", 14, null, null, null), name);
        kv.put(ImageUtil.getImageMapKey(100, 100, "songti", "bold", 14, null, null, null), sex);
        kv.put(ImageUtil.getImageMapKey(210, 100, "songti", "bold", 14, null, null, null), nation);
        kv.put(ImageUtil.getImageMapKey(100, 140, "songti", "bold", 14, null, null, null), birthDay);
        if (address1 != null) {
            kv.put(ImageUtil.getImageMapKey(100, 180, "songti", "bold", 14, null, null, null), address1);
        }
        if (address2 != null) {
            kv.put(ImageUtil.getImageMapKey(100, 198, "songti", "bold", 14, null, null, null), address2);
        }
        if (address3 != null) {
            kv.put(ImageUtil.getImageMapKey(100, 216, "songti", "bold", 14, null, null, null), address3);
        }
        kv.put(ImageUtil.getImageMapKey(170, 278, "songti", "bold", 14, null, null, null), idCard);


        byte[] bytes2 = ImageUtil.addString(imageByte, kv);

        return bytes2;
    }

    //获取名字
    private static String getGajNameByIdCard(String idCard) {
        String gonganju = "开发新区";
        String privince = idCard.substring(0, 2);
        Map<String, Object> onePrivince = provinceMap.get(privince);
        if (!CollectionUtils.isEmpty(onePrivince)) {
            Map<String, String> cityMap = (Map<String, String>) onePrivince.get("2");
            if (!CollectionUtils.isEmpty(cityMap)) {
                String city = idCard.substring(2, 6);
                gonganju = cityMap.get(city);
            }
        }

        if (StringUtils.isNotBlank(gonganju) && !gonganju.contains("局")) {
            gonganju += "公" + "安" + "局";
        }
        return gonganju;
    }

    public static byte[] genBackImage(String idCard) throws Exception {
        String gonganju = getGajNameByIdCard(idCard);
        String startValid = DateUtil.getDate(-365 * 3);
        String endValid = DateUtil.getDate(365 * 7);
        return genBackImage(gonganju, startValid, endValid);
    }

    //背面图片
    //key的格式： x_y_sognti_style_frontSize_R_G_B   value是写的字符串的值
    public static byte[] genBackImage(String gonganju, String startValid, String endValid) throws Exception {
        String url = BASE_URL + "/template/idCard_back.png";
        byte[] imageByte = getImageByte(url);
        if (imageByte == null || imageByte.length < 10) {
            return null;
        }

        //key的格式： x_y_sognti_style_frontSize_R_G_B   value是写的字符串的值
        Map<String, String> kv = new HashMap<>();
        String validate = (startValid != null ? startValid.replaceAll("-", ".") : "") + " - " + (endValid != null ? endValid.replaceAll("-", ".") : "");
        kv.put(ImageUtil.getImageMapKey(195, 234, "songti", "bold", 14, null, null, null), gonganju);
        kv.put(ImageUtil.getImageMapKey(195, 272, "songti", "bold", 14, null, null, null), validate);
        byte[] bytes2 = ImageUtil.addString(imageByte, kv);

        return bytes2;
    }

    public static void main(String[] args) throws Exception {
        byte[] genFrontImage = genFrontImage("孙艳强", "421126199202286019", "湖北省北京市省北京市省北省北京市京市省北京市省北京市省北京市省北京市省北京市", "汉");
        byte[] genBackImage = genBackImage("421100199202286019");
        MinioUtil.uploadFile("image/genFrontImage.png", genFrontImage);
        MinioUtil.uploadFile("image/genBackImage.png", genBackImage);
    }
}
